package com.zr.legalfactory.service.imp;

import com.zr.legalfactory.mapper.LegalFactoryMapper;
import com.zr.legalfactory.meiju.StatusEnum;
import com.zr.legalfactory.pojo.*;
import com.zr.legalfactory.service.LegalFactoryService;
import com.zr.legalfactory.util.PageUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by 陈紫陌 on 2019-10-08.
 */

@Service
public class LegalFactoryServiceImp implements LegalFactoryService {
    @Autowired
    private LegalFactoryMapper legalFactoryMapper;


    @Override
    public ResultVo ofCurrentUser(String username) {
//        查询法人名称
        List<Corporate> list = legalFactoryMapper.queryLegal(username);
        if (!CollectionUtils.isEmpty(list)){
            return ResultVoBuild.success(list);
        }
        return ResultVoBuild.error("500", ErrorMessageConfigration.FRXXBCZ);
    }

    //分页查询
    @Override
    public ResultVo query(@Valid PageVo pageVo) {
        PageUtil<Factory> pageUtil = new PageUtil<>();
        pageUtil.setpageSize(pageVo.getPageSize());
        pageUtil.setpageIndex(pageVo.getPageIndex());
        Integer offset = pageUtil.getOffset(pageUtil.getpageIndex(), pageUtil.getpageSize());
        Integer pageCount = pageUtil.getpageSize();
        pageVo.setOffset(offset);
        int count = legalFactoryMapper.queryCount(pageVo);
        pageUtil.settotalNumber(count);
        pageUtil.gettotalPage(count, pageCount);
        List<Factory> list = legalFactoryMapper.queryList(pageVo);
        pageUtil.setdataList(list);

        return ResultVoBuild.success(pageUtil);
    }

    //添加
    @Override
    @Transactional
    public ResultVo add(@Valid AddVo addVo) {
        Factory factory = new Factory();
        Date date = new Date();
//        查询cid
        Corporate corporate = legalFactoryMapper.queryCid(addVo);
        BeanUtils.copyProperties(addVo, factory);
        factory.setCid(corporate.getId());
        factory.setCreateName("王");
        factory.setUpdateName("找");
        factory.setUpdateTime(date);
        factory.setCreateTime(date);
        int i = legalFactoryMapper.add(factory);
        if (i>0){
            return ResultVoBuild.success(null);
        }
        return ResultVoBuild.error("500", ErrorMessageConfigration.TJSB);
    }

    //启用禁用
    @Override
    @Transactional
    public ResultVo update(@Valid UpdateVo updateVo) {
//       验证数据是否存在
        Factory factory = legalFactoryMapper.queryData(updateVo);
        if (factory==null){
            return ResultVoBuild.error("500", ErrorMessageConfigration.SJBCZ);
        }
//      在“启用”状态下，不允许修改“工厂描述”
        if (factory.getEnabled()==1){
            return ResultVoBuild.error("500", ErrorMessageConfigration.DQWQYZT);
        }
        Factory factory1 = new Factory();
        BeanUtils.copyProperties(updateVo, factory1);
//      修改
        Date date = new Date();
        factory1.setUpdateTime(date);
        factory1.setUpdateName("王五");
        int i = legalFactoryMapper.update(factory1);
        if (i>0){
                return ResultVoBuild.success(null);
        }
        return ResultVoBuild.error("500", ErrorMessageConfigration.XGSB);
    }

    //是否修改成功
    @Override
    @Transactional
    public ResultVo updatestatus(OnOffVo onOffVo) {
        int i = legalFactoryMapper.updatestatus(onOffVo);
        if (i>0){
            return ResultVoBuild.success(null);
        }
        return ResultVoBuild.error("500", ErrorMessageConfigration.XGSB);
    }


    @Override
    public CorporateBo queryBo(int id) {
        CorporateBo corporateBo = legalFactoryMapper.queryBo(id);
        return corporateBo;
    }

    @Override
    public List<CorporateBo> queryList(List<Integer> ids) {
        List<CorporateBo> list = legalFactoryMapper.queryList1(ids);
        return list;
    }

    @Override
    public ResultVo importFile(MultipartFile multipartFile) throws Exception{
        //        1.给用户提供导入模板
//        2.提示版本问题，询问产品经理支持哪种版本的导入格式，2007版本的导入模板，根据版本不同，poi导入技术的读取方式不同
        String filename = multipartFile.getOriginalFilename();
        if (!filename.contains("xlsx")){
            return ResultVoBuild.error("必须是2007版本");
        }
//        3.模板是否是需要导入的模板，验证模板是否正确(验证标头信息和列名，如果模版正确获取每一行的数据)
//        4.格式问题，必须保持统一格式，统一为字符串格式导入
        ResultVo<List<AddVo>> resultVo = validateFile(multipartFile);
        if (!resultVo.getSuccess()){
            return ResultVoBuild.error("模版不对");
        }
        //        5.验证不为空字段是否为空
//        6.验证字符长度是否符合需求
        ResultVo<List<AddVo>> check = check(resultVo.getData());
        if (!check.getSuccess()){
            return check;
        }
//        8.验证数据是否重复,和其他需求
        ResultVo<List> repeat = checkRepeat(check.getData());
        if (!repeat.getSuccess()){
            return repeat;
        }
//        7.添加的时候验证数据在数据库中是否存在
//        9.对于需要转换的数据进行数据转换，比如数据库存的数据为数字格式，用户输入的为汉字，需要把汉字转换为数字存储
        ResultVo addList = addList(check.getData());
        if (!addList.getSuccess()){
            return addList;
        }

        return null;
    }

    //        验证数据在数据库中是否存在
    private ResultVo addList(List<AddVo> data) {
        ResultVo assigement = assigement(data);
        if (!assigement.getSuccess()){
            return assigement;
        }
        List<Factory> factories = copy(data);
        int i = legalFactoryMapper.addList(factories);
        return ResultVoBuild.success();
    }

    //给创建人和创建时间等参数赋值
    private List<Factory> copy(List<AddVo> data) {
        List<Factory> factories = new ArrayList<>();
        Date nowDate = new Date();
        for (AddVo a:data){
            Factory factory = new Factory();
            BeanUtils.copyProperties(a,factory);
            factory.setCreateName("小明");
            factory.setCreateTime(nowDate);
            factory.setUpdateName("小明");
            factory.setUpdateTime(nowDate);
            factories.add(factory);
        }
        return factories;
    }

    // 验证数据在数据库中是否存在
    private ResultVo assigement(List<AddVo> data) {
        List<String> plantCodeList = new ArrayList<>();
        for (AddVo a : data) {
            plantCodeList.add(a.getLegalPlantCode());
        }
        List<String> list = legalFactoryMapper.queryNames(plantCodeList);
        if (!list.isEmpty()){
            return ResultVoBuild.error("已经存在的工厂编码"+list.toString());
        }
        return ResultVoBuild.success();
    }

    // 8.验证数据是否重复
    private ResultVo<List> checkRepeat(List<AddVo> data) {
        List<String> plantCodeList = new ArrayList<>();
        List<String> personCodeList = new ArrayList<>();
        for (AddVo a : data) {
            plantCodeList.add(a.getLegalPlantCode());
            personCodeList.add(a.getLegalPersonCode());
        }
        List<String> newPlantCodeList = new ArrayList<>();
        List<String> repeatePlantCodeList = new ArrayList<>();
        for (String s : plantCodeList) {
            if (!newPlantCodeList.contains(s)){
                newPlantCodeList.add(s);
            }else {
                repeatePlantCodeList.add(s);
            }
        }
        if (!repeatePlantCodeList.isEmpty()){
            return ResultVoBuild.error("存在重复的名称，重复的名称为:"+repeatePlantCodeList.toString());
        }
        return ResultVoBuild.success(data);
    }

    private ResultVo<List<AddVo>> check(List<AddVo> addVoList) {
        //        5.验证不为空字段是否为空
//        6.验证字符长度是否符合需求

        int i = 2;
        for (AddVo addVo : addVoList) {
            i++;
            if (StringUtils.isEmpty(addVo.getLegalPlantCode())){
                return ResultVoBuild.error("第"+i+"行的工厂编码不能为空");
            }else if (addVo.getLegalPlantCode().length()>100){
                return ResultVoBuild.error("第"+i+"行的工厂编码的长度不能超过100");
            }
            if (StringUtils.isEmpty(addVo.getLegalPersonCode())){
                return ResultVoBuild.error("第"+i+"行的法人编码不能为空");
            }else if (addVo.getLegalPersonCode().length()>100){
                return ResultVoBuild.error("第"+i+"行的法人编码的长度不能超过100");
            }
            if (StatusEnum.getValue(addVo.getEnabledName())==null){
                return ResultVoBuild.error("第"+i+"行的状态只能是禁用和启用");
            }else if (addVo.getEnabledName().length()>100){
                return ResultVoBuild.error("第"+i+"行的法人名称的长度不能超过100");
            }
        }
        return ResultVoBuild.success(addVoList);
    }

    private ResultVo validateFile(MultipartFile multipartFile) throws Exception {
        //        模板是否是需要导入的模板，验证模板是否正确
        //poi核心类，用来读取excel表格中的数据
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(multipartFile.getInputStream());
        //获取单元格中的信息 at0是获取sheet1中的数据。
        XSSFSheet sheetAt = xssfWorkbook.getSheetAt(0);
        //验证第一列第一行的表格标头信息是否为 “法人工厂导入模板”，如果不是，提示模板错误。
        if (!String.valueOf(sheetAt.getRow(sheetAt.getFirstRowNum()).getCell(0)).equals("法人工厂导入模板")){
            return ResultVoBuild.error("模版不对,请检查模版");
        }
//        验证第二行，即列名是否正确
        int twoRow = sheetAt.getFirstRowNum()+1;
        XSSFRow twoRowData = sheetAt.getRow(twoRow);
        if (twoRowData!=null){
//            cell从0开始
            if (!String.valueOf(twoRowData.getCell(0)).equals("序号")||
                    !String.valueOf(twoRowData.getCell(1)).equals("工厂编码")||
                    !String.valueOf(twoRowData.getCell(2)).equals("法人编码")||
                    !String.valueOf(twoRowData.getCell(3)).equals("状态")||
                    !String.valueOf(twoRowData.getCell(4)).equals("工厂描述")
                    ){
                return ResultVoBuild.error("列名不对，请检查列名。列名依次是序号、工厂编码、法人编码、状态、工厂描述");
            }
        }
        //遍历excel表格中的所有数据，从第五行开始读取，没有数据时终止遍历。
        List<AddVo> list = new ArrayList<>();
        //sheetAt.getFirstRowNum从1开始
        for (int i = sheetAt.getFirstRowNum()+2;i<=sheetAt.getLastRowNum();i++){
            //读取每一行的数据
            XSSFRow row = sheetAt.getRow(i);
//            判断不能空的数据是否为空(如果有空的数据我需要提示那个为空)
            if (row!=null){
                if (!String.valueOf(row.getCell(1)).equals("")||
                        !String.valueOf(row.getCell(2)).equals("")||
                        !String.valueOf(row.getCell(3)).equals("")){
//                    把每一行的数据放到实体类中
                    AddVo addVo =  addDataToPojo(row);
//                    把数据放到集合中
                    list.add(addVo);
                }
            }
        }
            return ResultVoBuild.success(list);
    }

    private AddVo addDataToPojo(XSSFRow row) {
        AddVo addVo = new AddVo();
        addVo.setLegalPlantCode(String.valueOf(row.getCell(1)));
        addVo.setLegalPersonCode(String.valueOf(row.getCell(2)));
        Integer value = StatusEnum.getValue(String.valueOf(row.getCell(3)));
        addVo.setEnabled(value);
        addVo.setEnabledName(String.valueOf(row.getCell(3)));
        System.out.println(String.valueOf(row.getCell(4)));
        addVo.setLegalPlantDec(String.valueOf(row.getCell(4)));
        Corporate corporate = legalFactoryMapper.queryCid(addVo);
        addVo.setCid(corporate.getId());
        return addVo;
    }


}
